package com.sjs.boot.dynamic.service.impl;

import cn.hutool.core.map.MapUtil;
import cn.hutool.core.util.StrUtil;
import com.sjs.boot.dynamic.core.config.method.MethodConfig;
import com.sjs.boot.dynamic.core.config.method.Methods;
import com.sjs.boot.dynamic.core.run.MethodContext;
import com.sjs.boot.dynamic.facade.run.AbstractRequester;
import com.sjs.boot.dynamic.http.exception.PlatformException;
import com.sjs.boot.dynamic.protocol.Const;
import com.sjs.boot.dynamic.protocol.RetCode;
import com.sjs.boot.dynamic.service.RequestDispatcherService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;

/**
 * @author uto_dev_008
 * @desc 请求处理
 * @since 2021/12/23 17:30
 * Copyright (c) 2021 南京友拓信息技术有限公司 All rights reserved
 */
@Service
public class RequestDispatcher implements RequestDispatcherService {
    private static final Logger logger = LoggerFactory.getLogger(RequestDispatcher.class);

    public RequestDispatcher() {
        logger.error("init requestDispatcher");
    }

    @Override
    public String getMethod(HttpServletRequest req, HttpServletResponse resp) {
//        String rec = req.getParameter(Dispatcher.PARA_RESOURCE);//获取资源号
        String rec = req.getRequestURI();
        if (StrUtil.isEmpty(rec)) {
            logger.warn("Resource is empty");
            return null;
        }

        String ver = req.getParameter(Const.PARA_VERSION); //版本必须作为REST参数传入
        if (ver == null || ver.equals("")) {
            ver = "1";
        }

        return ver + rec;
    }

    @Override
    public boolean process(HttpServletRequest req, HttpServletResponse resp) {
        String method = getMethod(req, resp);
        if (StrUtil.isEmpty(method)) {
            throw new PlatformException(RetCode.ERROR_404.getMsg(), RetCode.ERROR_404.getCode());

        }
        MethodConfig methodConfig = Methods.get(method);
        if (methodConfig == null) {
            logger.warn("Fail to get method {}", method);
            return true;
//            throw new PlatformException(DapRetCode.ERROR_404.getMsg(), DapRetCode.ERROR_404.getCode());
        }
        //构建请求的会话
        MethodContext context = new MethodContext(methodConfig, req, resp);
        Map<String, Object> parameters = new HashMap<String, Object>();
        context.setParameters(parameters);
        AbstractRequester requester = methodConfig.getRequester();
        int retCode;
        if ((retCode = requester.buildParameters(context, parameters)) == RetCode.OK.getCode()) {
            if (retCode == RetCode.OK.getCode() && (retCode = requester.checkRequest(context)) == RetCode.OK.getCode()) {
                return true;
            }
        }
        if (retCode != RetCode.OK.getCode()) {
            logger.info(context.getResults().toString());
            throw new PlatformException(MapUtil.getStr(context.getResults(), methodConfig.getReasonName()), retCode, false);
        }

        return true;
    }
}
